package com.ql.controller.sbglController;

import com.ql.pojo.sheBeiGuanLi.SheBeiKuCun;
import com.ql.pojo.user.Keshi;
import com.ql.service.keshi.KeShiService;
import com.ql.service.sbglService.SBCKService;
import com.ql.utils.Constrants;
import com.ql.utils.DateUtils;
import com.ql.utils.PageHelper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/sbgl/")
public class SBKCController {
    @Resource
    private SBCKService sbckService;
    @Resource
    private KeShiService keShiService;

    /*
        1.普通查询：解决：1)电话加密；2)日期格式化；3)角色表关联
        2.加入分页
     */
    @RequestMapping("getAll")
    public String getAll(@RequestParam(value = "shebeiName",required = false)String shebeiName,
                         @RequestParam(value = "zhuangtai",required = false)String zhuangtai,
                         @RequestParam(value = "keshiId",required = false)String keshiId,
                         @RequestParam(value = "mohuName",required = false)String mohuName,
                         Model model, PageHelper ph){//接受currentPageNo,totalCount,totalPageCount
        //开始进入Conroller keshiId为null，将keshiId转换成String “0” 不能将 null 转Integer类型
        if (shebeiName == null || shebeiName.equals("")){
            shebeiName = "";
        }
        if (zhuangtai == null){
            zhuangtai = "";
        }
        if (keshiId == null || keshiId.equals("")){
            keshiId = "0";
        }
        if (mohuName == null || mohuName.equals("")){
            mohuName = "";
        }
        //add:查询中带入分页条件:currentPageNo page-size
        List<SheBeiKuCun> sheBeiKuCunList=sbckService.getAllSheBeiKuCun(ph,shebeiName,zhuangtai,Integer.parseInt(keshiId),mohuName);
        model.addAttribute("sheBeiKuCunList",sheBeiKuCunList);//查询所有库存
        model.addAttribute("currentPageNo",ph.getCurrentPageNo());//当前页
        model.addAttribute("totalCount",ph.getTotalCount());//总条数
        model.addAttribute("totalPageCount",ph.getTotalPageCount());//总页数
        model.addAttribute("keShiService",keShiService.getAllKeShi());//查询所有科室
        model.addAttribute("shebeiName",shebeiName);
        model.addAttribute("zhuangtai",zhuangtai);
        model.addAttribute("keshiId",keshiId);
        model.addAttribute("mohuName",mohuName);
        return "sbgl";
    }

    //单个删除
    @RequestMapping("del/{sId}")
    @ResponseBody
    public String del(@PathVariable("sId")int sId){
        if(sbckService.removeSBCK(sId)){
            String msg = "{\"retMsg\":true}";
            return msg;
        }else{
            String msg = "{\"retMsg\":false}";
            return msg;
        }
    }

    //批量删除
    @RequestMapping("delBatch")//ajax的访问路径
    @ResponseBody//显示是以json格式返回，如果不加  返回一个视图
    public String delBatch(@RequestParam("delList")String[] delList){
        String regEx="[^0-9]";//java里的正则表达式，验证是否是数字
        List<Integer> list = new ArrayList<>();//要传到service层的list
        String result="{\"msg\":\"failed\"}";//返回的json  默认删除失败
        if(delList.length>0) {//如果前台传来的值为空，则不进行service层的调用.则list的长度为0
            for (int i = 0; i < delList.length; i++) {
                Pattern p = Pattern.compile(regEx);//构造java里的正则表达式类
                Matcher m = p.matcher(delList[i]);//进行匹配   m的值为每次循环的值（数字）
                list.add(Integer.valueOf(m.replaceAll("").trim()));//替换所有空格和换行
            }
        }
        if(list.size()>0){//传入service的list  如果list不为空，则传入service  否则不进行数据库操作
            if(sbckService.deleteBatch(list)){//进行service层的方法。如果删除成功  进入if  否者进入else
                result="{\"msg\":\"success\"}";//删除成功，修改返回的json
            }else{
                result="{\"msg\":\"failed\"}";
            }
        }
        return result;//返回json
    }
    //获取id查询库存信息
    @RequestMapping("seesbkc")
    public String getSeeSBKC(@RequestParam(value = "sId",required = false)String sId,Model model){
        SheBeiKuCun sheBeiKuCun=sbckService.getKCById(sId);
        model.addAttribute("sheBeiKuCun",sheBeiKuCun);
        return "seesbkc";
    }
    //拿到新增信息
    @RequestMapping("goAdd")
    public String goAdd(Model model){
        List<Keshi> keshis = keShiService.getAllKeShi();
        model.addAttribute("keshis",keshis);
        return "sbgl_add";
    }
//    新增库存
    @RequestMapping("add")
    public String addSBKC(@ModelAttribute("sbkc")SheBeiKuCun sheBeiKuCun,String TrukuTime, HttpSession session,Model model)throws Exception{
        if(null==session.getAttribute(Constrants.USER_SESSION)){
            //调用增加方法
            sheBeiKuCun.setRukuTime(DateUtils.parse(TrukuTime));
            if(sbckService.addNewSBKC(sheBeiKuCun)){
                return "sbglSuccess";
            }else{
//                return "redirect:getAll";
                return "sbglErrer";
            }
        }else {
            return "sbglSuccess";
        }
    }
    //修改拿到信息
    @RequestMapping("goUpdate")
    public ModelAndView goUpdate(@RequestParam("sId")String sId, Model model){
        List<Keshi> keshis = keShiService.getAllKeShi();
        SheBeiKuCun sheBeiKuCun=sbckService.getKCById(sId);
        model.addAttribute("keshis",keshis);
        return new ModelAndView("sbgl_edit","sheBeiKuCun",sheBeiKuCun);
    }
    //修改库存
    @RequestMapping("update")
    public String modifyBySBKC(@RequestParam("sId")String sId,@RequestParam("xzId")String xzId,@RequestParam("zt")String zt,@RequestParam("sbCode")String sbCode,
                               @RequestParam("keshi")String keshi,@RequestParam("cpUse")String cpUse,@RequestParam("cpType")String cpType,@RequestParam("sbType")String sbType,
                               @RequestParam("sbNumber")String sbNumber,@RequestParam("xiugaiTime")String xiugaiTime,@RequestParam("modified")String modified,
                               HttpSession session,Model model){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date shijian = new Date();
        try {
            shijian = simpleDateFormat.parse(xiugaiTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SheBeiKuCun sheBeiKuCun=new SheBeiKuCun(Integer.parseInt(sId),xzId,zt,sbCode,sbType,cpType,cpUse,Integer.parseInt(keshi),Integer.parseInt(sbNumber),shijian,modified);
       if(sbckService.updateSBKC(sheBeiKuCun)){
            return "sbglSuccess";
        }else {
           return "sbglErrer";
       }
    }
}
